﻿/****************
 * Copyright 2016 Brian Tabone
 * Licensed under the Apache 2.0 License
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Adapted from: https://msdn.microsoft.com/en-us/library/fx6588te(v=vs.110).aspx
 * MessageChannel.cs
 * Implements the IMessageChannel interface to provide control channel support for services
 * 8/8/16
 */

using System;
using IAO.Common.Interfaces.Networking;
using Microsoft.Owin.Hosting;

namespace IAO.Common.Network
{
    /// <summary>
    ///     Provides the Message Passing Channel support. Each service has a single instance of this channel and receives
    ///     command and reporting requests from this channel.
    ///     Messages here are transactional in nature
    /// </summary>
    public class MessageChannel : IMessageChannel
    {
        /// <summary>
        ///     Start the message channel on the host and port binding
        /// </summary>
        /// <param name="host"></param>
        /// <param name="port"></param>
        public MessageChannel(string host, ushort port)
        {
            if (host == null)
            {
                throw new ArgumentException("Host must be defined, use localhost or 127.0.0.1 for local computer");
            }

            if (port == 0)
            {
                throw new ArgumentException("Port must be greater than 0");
            }

            Host = host;
            Port = port;
        }

        private string BaseAddress
        {
            get { return $"http://{Host}:{Port}/"; }
        }

        /// <summary>
        ///     The web app reference (used to control such as shutting down)
        /// </summary>
        private IDisposable RESTApp { get; set; }

        public string Host { get; }

        public ushort Port { get; }

        public ListeningState State { get; }

        void IMessageChannel.StartListening()
        {
            RESTApp = WebApp.Start<Startup>(BaseAddress);
        }

        void IMessageChannel.StopListening()
        {
            RESTApp.Dispose();
        }
    }
}